<template>
  <div class="myContainer">
    <el-row class="myBorderBottom">
      <el-col :span="3" class="myTitleText myLineHeight_40px">能耗管理</el-col>
      <el-col :span="16" class="myLineHeight_40px">
        当日 : <span>{{electCurrent}}  | {{waterCurrent}}</span>&nbsp;&nbsp;&nbsp;&nbsp;
        当月 : <span>{{electMonthly}}  | {{waterMonthly}}</span>
      </el-col>
      <el-col :span="5" class="myTextAlignRight">
        <el-button type="primary" class="myBgGreen" @click="onOpen" v-if="isShow(210)">告警阀值设定</el-button>
        <!-- <el-button type="primary" class="myBgGreen" @click="onCount">统计分析</el-button>
        <el-button type="primary" class="myBgGreen">告警日志</el-button> -->
      </el-col>
    </el-row>
    <!-- 搜索部分 start -->
    <el-row :gutter="10" class="myPaddingTop_10px">
      <el-col :span="6">
        <template>
            <el-cascader
            placeholder="全部项目/小区"
            :options="regionOptions"
            v-model="regionOptSelected"
            ></el-cascader>
        </template>
      </el-col>
      <el-col :span="4">
        <template>
          <el-select v-model="pubEnergyAlarmTypeSelected"
            clearable
            placeholder="全部状态">
            <el-option
              v-for="item in Object.keys(pubEnergyAlarmType)"
              :key="pubEnergyAlarmType[item]"
              :label="pubEnergyAlarmType[item]"
              :value="item">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="4">
        <template>
          <el-select v-model="pubEnergyTypeSelected"
            clearable
            placeholder="全部耗能类型">
            <el-option
             v-for="item in Object.keys(pubEnergyType)"
              :key="pubEnergyType[item]"
              :label="pubEnergyType[item]"
              :value="item">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="4">
        <el-button @click="handleSearchClick" type="primary" class="myBgGreen">查 询</el-button>
      </el-col>
    </el-row>
    <!-- 搜索部分 end -->
    <el-row class="mymarginTop_10px">
      <el-col :span="24">
        <template>
          <el-table
            border
            v-loading="loading"
            :data="list"
            :row-class-name="tableRowClassName"
            style="width: 100%">
            <el-table-column
              label="序号"
              type="index"
              width="100">
            </el-table-column>
            <el-table-column
              label="节点名称"
              width="130"
              prop="dev_room_name">
            </el-table-column>
            <el-table-column
              label="能耗类型"
              width="100"
              prop="energy_type">
               <template scope="scope">
                <span>{{scope.row.energy_type| pubEnergyType}}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="当前状态"
              width="100"
              prop="is_alarm">
              <template scope="scope">
                <span>{{scope.row.is_alarm| isAlarm}}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="当日"
              width="120"
              prop="quantity">
            </el-table-column>
            <el-table-column
              label="当月"
              width="130"
              prop="monthly">
            </el-table-column>
            <el-table-column
              label="责任人"
              width="120"
              prop="duty_user_name">
            </el-table-column>
            <el-table-column
              label="联系电话"
              width="130"
              prop="duty_user_phone">
            </el-table-column>
            <el-table-column
              label="物理地址"
              prop="display_room_name">
            </el-table-column>
            <el-table-column
              label="所属小区"
              prop="area_name">
            </el-table-column>
            <el-table-column
              label="功能操作"
              width="100">
              <template scope="scope">
                <el-button class="look" type="text" size="small" @click="handleDetailDlg(scope.row)">详情</el-button> 
                <!-- | <el-button class="look" type="text" size="small" @click="onHistoricalRecord">历史记录</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-col>
    </el-row>
    <!--  @click="detailsDialogVisible = true" -->
    <!-- 分页控件 start -->
    <div class="block">                    
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page_num"
        :page-sizes="[10, 15]"
        :page-size="page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 分页控件 end -->


    <!--阀值设定弹出框 start-->
    <el-dialog title="告警阀值设定" class="myRoleDialog" :visible.sync="thresholdDialogVisible">
      <el-row class="mymarginTop_10px">
        <el-col :span="5" class="myLeftMsg">
          用水量阀值 :
        </el-col>
        <el-col :span="17">
          <el-input placeholder="用水量阀值" v-model="water_threshold"></el-input>
        </el-col>
        <el-col :span="2" class="myLeftMsg">
          %
        </el-col>
      </el-row>
      <el-row class="mymarginTop_10px">
        <el-col :span="5" class="myLeftMsg">
          用电量阀值 :
        </el-col>
        <el-col :span="17">
          <el-input placeholder="用电量阀值" v-model="electricity_threshold"></el-input>
        </el-col>
        <el-col :span="2" class="myLeftMsg">
          %
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="myBgGreen" @click="onSeva">保 存</el-button>
        <el-button type="primary" class="myBgGreen" @click="thresholdDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 阀值设定弹出框 end-->
    
    <!-- 查看详情弹出框 start -->
    <el-dialog :title="detail.dev_room_name" class="mynhgl" :visible.sync="detailDialogVisible">
      <div class="modal-body">
        <el-row class="mymarginTop_10px">
          <el-col :span="24">
            <el-row>
              责任人 : <span v-if="detail.duty_user_name!=''">{{detail.duty_user_name}}</span><span v-else>无</span>
              联系电话 : <span v-if="detail.duty_user_phone!=''">{{detail.duty_user_phone}}</span><span v-else>无</span>
              状态 : <span>{{detail.is_alarm| isAlarm}}</span>
            </el-row>
            <el-row>
              当日用量 : <span>{{detail.quantity}}</span>
              当月累计 : <span>{{detail.monthly}}</span>
              七日平均用量 : <span>{{average}}</span>
              <!-- 增幅 : <span>+300%</span> -->
            </el-row>
          </el-col>
        </el-row>
        <el-row class="mymarginTop_10px">
          <el-col :span="24">
            近7日用量走势图 ：
          </el-col>
        </el-row> 
        <el-row class="mymarginTop_10px">
          <el-col :span="24">
            <vue-highcharts :options="options" ref="lineChart" style="width:700px; height:200px;"></vue-highcharts>
            <!-- <div class="container" style="width:700px; height:200px;"></div> -->
          </el-col>
        </el-row>  
      </div>
      <div class="modal-footer myTextAlignRight">
        <el-button @click="detailDialogVisible = false" type="primary" class="myBgGreen" data-dismiss="modal">关 闭</el-button>
      </div>
  </el-dialog>
    <!-- 查看详情弹出框 end -->
  </div>
  </div>
</template>  

<style scoped>
  .myContainer{
    background: #fff;
    padding: 10px;
  }
  .myHeadeTitle{
    color: #000;
    font-weight: 500;
    font-size: 16px;
    padding-bottom: 10px;
    border-bottom: 1px solid #dbdbdb;
    margin-bottom:10px; 
  }
  .myHeadeTitle:before,.myHeadeTitle:after{
    content: " ";
    display: block;
    clear: both;
  }
  .myBgGreen{
    background: #00c2a9;
    border-color: #00c2a9;
    color: #fff;
    margin-top: 2px;
  }
  .myLineHeight_35px{
    line-height: 35px;
  }
  .myTextAlignRight{
    text-align: right;
  }
  .myBgGreen:hover{
    background: #33ceba;
  }
  .myPaddingTop_10px{
    padding-top: 10px;
  }  
  .myLeftMsg{
    line-height: 40px;
    text-align: right;
    padding-right: 10px;
  }
  .myPaddingBottom_10px{
    padding-bottom: 10px;
  }
  .myVA_M{
    vertical-align: middle;
  }
  .myPadding_20px{
    padding: 20px;
  }    
  .myTitleText{
    font-weight: 500;
    font-size: 16px;
  }
  .myLineHeight_40px{
    line-height: 40px;
  }
  .myBorderBottom{
    border-bottom:1px solid #dbdbdb;
    padding-bottom: 5px;
  }
  .mymarginTop_10px{
    padding-top: 10px;
  }
  
</style>

<script>
import { extractAreaIds } from '@/utils/misc';
import { getRegion } from '@/utils/localstorage';
import VueHighcharts from 'vue2-highcharts';
import { getCurrentPubEnergyList, getCurrentPubEnergyTotal, getPubEnergyTrend, pubEnergyAlarmType, pubEnergyType , getThreshold , setThreshold } from '@/api/pub_energy';

  export default {
     data(){
      return{
        loading: false,
        num:0,
         // 搜索条件
        // 小区选择
        regionOptions: [],
        regionOptSelected: [],

        // 能耗告警级别及类型
        pubEnergyAlarmTypeSelected: null,
        pubEnergyAlarmType: pubEnergyAlarmType,
        pubEnergyTypeSelected: null,
        pubEnergyType: pubEnergyType,

        // 当前时间
        currentDate: '',

        // 当日水、电总数
        waterCurrent: '',
        electCurrent: '',

        // 当月水、电总数
        waterMonthly: '',
        electMonthly: '',

        // 列表数据
        list:[],
        page_num:1,
        page_size:10,
        total:null,

        //阈值
        water_threshold:"",
        electricity_threshold:"",

        // 当前节点详情
        detail: {},
        detailDialogVisible: false,
        average: "",
        trend: [],
        // 趋势图相关
        options: {
        chart: {
            type: 'areaspline'
        },
        title: {
            text: '',//标题
            style:{
              fontSize:"16px"
            }
        },
        xAxis: {
          tickLength: 5,
          tickmarkPlacement: 'on',
          pointStart:0,
          categories: []
        },
        yAxis: {
            title: {
                text: ''
            },
            labels: {
                formatter: function () {
                    return this.value;
                }
            }
        },
        tooltip: {
            pointFormat: '{point.y:,.0f}'
        },
        credits:{
          enabled: false  //去掉版权信息
        },
        plotOptions: {
            area: {
              pointStart: 2002,
              marker: {
                enabled: false,
                symbol: 'circle',
                radius: 2,
                states: {
                  hover: {
                    enabled: false
                  }
                }
              }
            },
            series: {
              lineWidth: 0
            }
          },
          series: []
      },

      housValue:"",
      housOptions:[],
      value1:"",
      thresholdDialogVisible:false
      }
    },
    computed: {
      areaIds() {
        return extractAreaIds(this.regionOptSelected, this.regionOptions);
      }
    },
    components: {
     VueHighcharts 
    },
    filters: {
      pubEnergyType(value) {
        return pubEnergyType[value];
      },
      isAlarm(value) {
        if (value) {
          return '告警';
        } else {
          return '正常';
        }
      }
    },
    created(){
      document.title="能耗管理";
      this.regionOptions = getRegion();
      this.regionOptSelected.push(this.regionOptions[0].value,this.regionOptions[0].children[0].value,this.regionOptions[0].children[0].children[0].value);
      
      
      this.pubEnergyTypeSelected=this.$route.query.type?this.$route.query.type+'':'';

      let cd = new Date(); 
      this.currentDate = cd.getFullYear() + '-' + (cd.getMonth()+1) + '-' + cd.getDate();

      this.fetchCurrentPubEnergyList();
      this.fetchCurrentPubEnergyTotal();

    },
    methods:{
      fetchCurrentPubEnergyTotal() {
        let vm = this;
        let params = {
          date: vm.currentDate
        };
        getCurrentPubEnergyTotal(vm.areaIds)
        .then(response => {
          let res = response.data;
          for (let i = 0; i < res.length; i++) {
            if (res[i].energy_type == 1) {
              vm.waterCurrent = res[i].quantity;
              vm.waterMonthly = res[i].monthly;
            } else {
             vm.electCurrent = res[i].quantity;
              vm.electMonthly = res[i].monthly;
            }
          }
        })
        .catch(error => {

        })
      },
      fetchCurrentPubEnergyList() {
        let vm = this;
        let params = {
          start_date: vm.currentDate,
          end_date: vm.currentDate,
          status: vm.pubEnergyAlarmTypeSelected,
          energy_type: vm.pubEnergyTypeSelected,
          page_num: vm.page_num,
          page_size: vm.page_size
        }
        vm.loading = true;
        getCurrentPubEnergyList(vm.areaIds, params)
        .then(response => {
          let res = response.data;
          vm.list = res.rows;
          vm.page_num = res.page_num;
          vm.page_size = res.page_size;
          vm.total = res.total;

          vm.loading = false;
        })
        .catch(error => {

          vm.loading = false;
        })
      },
      fetchTrend(devRoomId, energyType) {
        let vm = this;
        if(vm.num!=0){
          vm.$refs.lineChart.removeSeries();
        }
        vm.num++;

        getPubEnergyTrend(devRoomId, energyType)
        .then(response => {
          vm.average = response.data.average;

          let res = response.data.data;
          let x = new Array(res.length);
          let s = new Array(res.length);
          for (let i = 0; i < res.length; i++) {
            x[i] = res[i].day_date;
            s[i] = parseInt(res[i].quantity);
          }

          vm.$refs.lineChart.getChart().xAxis[0].setCategories(x)
          vm.$refs.lineChart.getChart().addSeries({
            name: '近7日用量走势',
            data: s,
            color: '#a7eae1',
            marker: {
              enabled: false,  //去掉折线上圆点
            }})
        })
        .catch(error => {

          vm.$refs.lineChart.getChart().xAxis[0].setCategories([])
          vm.$refs.lineChart.getChart().addSeries({
            name: '近7日用量走势',
            data: [],
            color: '#a7eae1',
            marker: {
              enabled: false,  //去掉折线上圆点
            }})
        })
      },
      handleSearchClick() {
        this.fetchCurrentPubEnergyTotal();
        this.fetchCurrentPubEnergyList();
      },
      handleSizeChange(val) {//每页条数控制
        this.page_size = val;
        this.fetchCurrentPubEnergyList();
      },
      handleCurrentChange(val) {//每页
        this.page_num = val;
        this.fetchCurrentPubEnergyList();
      },
      handleDetailDlg(val) {
        this.detailDialogVisible = true;
        this.detail = val;

        this.fetchTrend(this.detail.dev_room_id, this.detail.energy_type);
      },
      onHistoricalRecord:function(){//去历史记录
        this.$router.push({
          path:"/nhjl"
        })
      },
      onCount:function(){//去统计分析
        this.$router.push({
          path:"/tjfx"
        })
      },
      onOpen(){
        let vm=this;
        vm.thresholdDialogVisible=true;
        getThreshold().then(response =>{
          let res=response.data;
          vm.water_threshold=res.water_threshold_value;//水阈值
          vm.electricity_threshold=res.electricity_threshold_value;//电阈值
          console.log(res)
        }).catch(error =>{  
          console.log(error)
        })
      },
      onSeva(){
        let vm=this;
        let params={
          water_threshold_value:vm.water_threshold,
          electricity_threshold_value:vm.electricity_threshold
        }
        setThreshold(params).then(response => {
          let res=response.data;
          vm.$message.success("执行成功！");
          vm.thresholdDialogVisible=false;
          console.log(res)
        }).catch(error => {
          vm.$message.error("执行失败！");
          console.log(error)
        })
      },
      tableRowClassName({row, rowIndex}) {
        if (row.is_alarm) {
          return 'warning-row';
        } else {
          //return 'success-row';
        }
        return '';
      }
    }

  }

</script>  



